


// // 内存缓存Reader, Writer: 基于Vec<u8>
use std::io::{self, Read};

/// 模仿：std::io::Cursor, 
/// bytes::BytesMut
pub struct BytesIO {
    pub name: String,
    pub(crate) bytes: Vec<u8>,
    pub(crate)pos: usize,
}
impl BytesIO {
    pub fn new(name: String) -> Self {
        Self {
            name,
            bytes: vec![],
            pos: 0,
        }
    }
    pub fn with_capacity(name: String, capacity: usize) -> Self {
        Self {
            name,
            bytes: Vec::with_capacity(capacity),
            pos: 0,
        }
    }

    pub fn pos(&self) -> usize {
        self.pos
    }

    pub fn len(&self) -> usize {
        self.bytes.len()
    }
    pub fn tell(&self) -> usize {
        self.pos
    }
    pub fn to_bytes_ref(&self) -> &Vec<u8> {
        &self.bytes
    }
    pub fn to_bytes(self) -> Vec<u8> {
        self.bytes
    }
}

impl BytesIO {
    pub fn from_bytes(name: String, bytes: Vec<u8>) -> Self {
        Self{
            name,
            bytes,
            pos: 0,
        }
    }
    // pub fn from_file(name: String, file: &str) -> Self {
    //     let (bytes, _msg) = file_io::read_bytes(file);
    //     Self{
    //         name,
    //         bytes,
    //         pos: 0,
    //     }


    // }

}



impl io::Read for BytesIO {
    fn read(&mut self, buf: &mut [u8]) -> io::Result<usize> {
        // if self.pos + buf.len() > self.bytes.len() {
        //     let msg = format!("BytesIO::read, end of memory: {}(pos) + {}(read) = {} > {}(len)",
        //         self.pos, buf.len(), self.pos + buf.len(), self.bytes.len());
        //     return Err(io::Error::new(io::ErrorKind::OutOfMemory, msg));
        // }
        let n = Read::read(&mut self.remaining_slice(), buf)?;
        self.pos += n;
        Ok(n)
    }
    
}

pub(crate) const LEN_1: usize = 1;
pub(crate) const LEN_2: usize = 2;
pub(crate) const LEN_4: usize = 4;
pub(crate) const LEN_8: usize = 8;
pub(crate) const LEN_16: usize = 16;





// block start: from io::Crusor =======================================================================
impl BytesIO {
    pub fn remaining_slice(&self) -> &[u8] {
        let len = self.pos.min(self.bytes.len());
        &self.bytes[len..]
    }
}
// // Non-resizing write implementation
// #[inline]
// fn slice_write(pos_mut: &mut usize, slice_dest: &mut [u8], buf_src: &[u8]) -> usize {
//     let pos = cmp::min(*pos_mut, slice_dest.len());
//     let amt = (&mut slice_dest[(pos as usize)..]).write(buf_src)?;
//     *pos_mut += amt;
//     Ok(amt)
// }
// // block end: from io::Crusor =======================================================================